﻿using UnityEngine;
using UnityEngine.UI;

public class AutoRanges : MonoBehaviour {

    public GaugeInfo gauge;
    public GameObject RangeImagePrefab;

    void Start () {
        GeneratRanges();
    }

    private void GeneratRanges()
    {
        if (null == gauge || null == RangeImagePrefab)
        {
            return;
        }
                
        if (null == gauge.ranges || 0 == gauge.ranges.Length)
        {
            return;
        }

        int count = gauge.ranges.Length;
        for (int i = 0; i < count; i++)
        {
            DoCreate(gauge.ranges[i]);
        }

    }

    GameObject newInstance;
    Image image;
    float fillAmonute;
    float angle;
    Vector2 scale;
    private void DoCreate(GaugeRange range)
    {
        newInstance = Instantiate<GameObject>(RangeImagePrefab);       

        image = newInstance.GetComponent<Image>();
        if (null == image)
        {
            return;
        }
        scale = image.rectTransform.localScale;

        newInstance.transform.SetParent(transform);
        newInstance.transform.localPosition = Vector3.zero;
        newInstance.transform.localScale = scale;

        fillAmonute = (gauge.maxAngle - gauge.minAngle) / 360 * (range.rangeMax - range.rangeMin) / (gauge.max - gauge.min);
        image.fillAmount = fillAmonute;

        image.color = range.rangeColor;

        angle = (-1 * range.rangeMin / gauge.max - gauge.min) * (gauge.maxAngle - gauge.minAngle) - 90 - gauge.minAngle;
        if (gauge.invert)
        {
            //float temp = (gauge.max - gauge.min) - (range.rangeMax - range.rangeMin) + range.rangeMin;
            float temp = gauge.max - range.rangeMax + gauge.min;
            angle = (-1 * temp / gauge.max - gauge.min) * (gauge.maxAngle - gauge.minAngle) - 90 - gauge.minAngle;
        }
        image.rectTransform.localRotation = Quaternion.Euler(0, 0, angle);
    }
}
